import 'dart:collection';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../event/DataCallBack.dart';
import '../event/WkEventListener.dart';
import '../style/app_colors.dart';
class CommonWidgets {

  static AppBar buildAppBar(BuildContext context, String title,) {
    return AppBar(
      backgroundColor: AppColors.app_base_bgcolor_color,
      title: Text(title),
      centerTitle: true,
      leading: IconButton(
        icon: Image.asset('assets/images/ic_back2.png',
            width: 48.w, height: 48.h),
        onPressed: () {
          Get.back();
        },
        tooltip: MaterialLocalizations.of(context).backButtonTooltip, // 可选：设置工具提示
      ),
    );
  }

  @deprecated
  static Widget getEditFiledWithValidatorAndLabel(
      String hint,
      TextEditingController controller,
      String label,
      String prefixText,
      String suffixText,
      {FormFieldValidator<String>? validator,
        int maxLength = 0, FocusNode? focusNode,
        bool suffixIconVisible = false}) {
    if (maxLength > 0) {
      return Container(
        decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              spreadRadius: 5,
              blurRadius: 7,
              offset: Offset(0, 8.sp), // changes position of shadow
            ),
          ],
          color:Colors.white,
          borderRadius: BorderRadius.circular(45), // Optional: add border radius
        ),
        child: TextFormField(
          focusNode: focusNode,
          decoration: InputDecoration(
              hintText: hint,
              labelText: label,
              prefixText: prefixText,
              suffixIcon: suffixIconVisible?Container(
                width: 36.w,
                height: 36.h,
                child: Image.asset('assets/images/ic_clear.webp'),
              ):SizedBox(),
              suffixIconConstraints: BoxConstraints(maxWidth: 36.w,maxHeight: 36.h)
          ),
          inputFormatters: [
            LengthLimitingTextInputFormatter(maxLength) //长度限制
          ],
          validator: validator,
          controller: controller,
        ),
      );
    } else {
      return Container(
        width: 600.w,
        height: 90.h,
        decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              spreadRadius: 5,
              blurRadius: 7,
              offset: Offset(0, 8.sp), // changes position of shadow
            ),
          ],
          color:Colors.white,
          borderRadius: BorderRadius.circular(45), // Optional: add border radius
        ),
        child: TextFormField(
          focusNode: focusNode,
          decoration: InputDecoration(
            hintText: hint,
            prefixText: prefixText,
           // suffixIcon: Image.asset('assets/images/ic_clear.webp',width: 36.w,height: 36.h),
           // suffixIconConstraints: BoxConstraints(maxWidth: 36.w,maxHeight: 36.h)
           suffixIcon: suffixIconVisible? Container(
             margin: EdgeInsets.only(right: 36.w),
             child: Image.asset('assets/images/ic_clear.webp',width: 36.w,height: 36.h),
           ):SizedBox(),
          ),
          validator: validator,
          controller: controller,

        ),
      );
    }
  }


  static showSingleBtnDialog(BuildContext context,String title,String content,  WkEventListener? wkEventListener,{String btnText = '确定'}) async {
    Widget okButton = ElevatedButton(
      child: Text(btnText),
      onPressed: () {
        Get.back();
        if(wkEventListener != null) {
          wkEventListener.onClick!('YES');

        }


      },
    );

    //设置对话框
    AlertDialog alert = AlertDialog(
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(height: 20.h),
          title == '' ? SizedBox():
          Text(title,style: TextStyle(fontSize: 34.sp,color: AppColors.Page_Title_Color,fontWeight: FontWeight.w600)),
          SizedBox(height: 20.h),
          Text(content,style: TextStyle(fontSize: 25.sp,color: AppColors.Page_Title_Color),),
          SizedBox(height: 50.h),
          Container(
            width: 300.w,
            child: okButton,
          ),
          SizedBox(height: 20.h),
        ],
      ),

    );

    //显示对话框
    showDialog<String>(
      context: context,
      barrierDismissible:false,
      builder: (BuildContext context) {
        return alert;
      },
    );


  }

  static showConfirmDialog (BuildContext context,String title,
      String content,String positiveTx,String negativeTx,
      DataCallBack? dataCallBack) async {

    //设置对话框
    AlertDialog alert = AlertDialog(
      content: Container(
        width: 640.w,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(height: 20.h),
            title == '' ? SizedBox():
            Text(title,style: TextStyle(fontSize: 34.sp,color: AppColors.Page_Title_Color,fontWeight: FontWeight.w600)),
            SizedBox(height: 20.h),
            Text(content,style: TextStyle(fontSize: 25.sp,color: AppColors.Page_Title_Color),),
            SizedBox(height: 20,),
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        child: ElevatedButton(onPressed: () {
                          dataCallBack!.confirmCallBack!('YES');
                          Get.back();

                        }, child: Container(

                          padding: EdgeInsets.only(left: 122.w,right: 122.w),
                          child: Text(positiveTx),
                        )),
                      ),
                      SizedBox(height: 20.h,),
                      Container(
                        child: ElevatedButton(onPressed: () {
                          dataCallBack!.cancleCallBack!('NO');
                          Get.back();

                        }, child: Container(
                          padding: EdgeInsets.only(left: 122.w,right: 122.w),
                          child: Text(negativeTx),
                        )

                        ),
                      )
                      ,


                    ],
                  )
                ],
              ),
            ),
            SizedBox(height: 20,),
          ],
        ),
      ),

    );

    showDialog<String>(
      context: context,
      barrierDismissible:false,
      builder: (BuildContext context) {
        return alert;
      },
    );





  }

  // 专门为帮助用的Dialog框.
  static showDialogForAssistantHelp (BuildContext context)  {
    //设置对话框
    AlertDialog alert = AlertDialog(
      backgroundColor:Colors.white,
      content: Container(
        width: 600.w,
        padding: EdgeInsets.only(left: 50.w),
        color: Colors.white,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('帮助',style: TextStyle(fontSize: 36.sp,fontWeight: FontWeight.bold),),
              ],
            ),
            SizedBox(height: 31.h),
            Text('1. 请确认机器人电源已打开;',style: TextStyle(fontSize: 28.sp),),
            SizedBox(height: 25.h),

            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset('assets/images/turn_on_robot.gif',width: 160.w,height: 369.h),
              ],
            ),
            SizedBox(height: 5.h),
            Text('2. 请将手机靠近机器人;',style: TextStyle(fontSize: 28.sp),),
            SizedBox(height: 17.h),
            Text('3. 如果仍无法搜索到机器人,',style: TextStyle(fontSize: 28.sp),),
            Text('请联系客服: 400-6666-700',style: TextStyle(fontSize: 28.sp),),
          ],
        ),
      ),

    );

    //显示对话框
   showDialog<String>(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );




  }


  static showConfirmDialogForUserProtocol (BuildContext context,
      DataCallBack? dataCallBack,GestureTapCallback? onTapUserAgreement , GestureTapCallback? onTapPrivacyPolicy) async {
    final TextStyle linkStyle = TextStyle(
      color: Colors.blue,
      fontSize: 28.sp
    );

    final TextStyle normal = TextStyle(
        color: AppColors.dialogTextColor,
        fontSize: 28.sp
    );


    //设置对话框
    AlertDialog alert = AlertDialog(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('个人信息保护提示')
          ],
        ),
        content: Container(
        width: 640.w,

        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('欢迎使用悟空机器人！'), //内容.
            SizedBox(height: 20.h,),
             RichText(
             text: TextSpan(
               children: [
                 TextSpan(text: '为了更好的保护您的权益，我们将通过', style: normal),
                 TextSpan(text: '《用户协议》',style: linkStyle,recognizer:TapGestureRecognizer()..onTap=onTapUserAgreement),
                 TextSpan(text: '和',style: normal),
                 TextSpan(text: '《隐私政策》',style: linkStyle,recognizer:TapGestureRecognizer()..onTap=onTapPrivacyPolicy),
                 TextSpan(text: '帮助您了解我们为您提供的服务、我们如何处理个人信息以及您享受的权利。我们会严格按照相关法律要求、采取各种安全措施来保护您的个人信息。',style: normal),

               ]
             ),
            ),

            //Text('为了更好的保护您的权益，我们将通过《用户协议》和《隐私政策》帮助您了解我们为您提供的服务、我们如何处理个人信息以及您享受的权利。我们会严格按照相关法律要求、才去各种安全措施来保护您的个人信息。'),
            SizedBox(height: 20.h,),
            Text('在您同意App隐私政策后，我们将进行集成SDK的初始化工作，会收集您的Android_id、IP、应用安装列表和位置信息，以保障App政策数据统计和安全风控。'),
            SizedBox(height: 20.h,),
            Text('点击“同意”按钮，表示您已知情并同意以上协议。'),

            SizedBox(height: 40.h,),
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        width: 480.w,
                        child: ElevatedButton(onPressed: () {
                          Navigator.of(context, rootNavigator: true).pop("YES");
                          dataCallBack!.confirmCallBack!('yes');

                        }, child: Text('同意')),
                      ),
                      SizedBox(height: 20.h,),
                      GestureDetector(
                        onTap: () {
                          Navigator.of(context, rootNavigator: true).pop("No");
                          dataCallBack!.cancleCallBack!('No');
                        },
                        child: Text('不同意并退出'),
                      )

                    ],
                  )
                ],
              ),
            )



          ],
        ),
      )
    );

    //显示对话框
    String? select = await showDialog<String>(
      context: context,
      barrierDismissible:false,
      builder: (BuildContext context) {
        return alert;
      },
    );

    if (select == "YES") {
      if (dataCallBack?.confirmCallBack != null) {
        dataCallBack?.confirmCallBack!("YES");
      }

    } else if (select == "NO") {
      if (dataCallBack?.cancleCallBack != null) {
        dataCallBack?.cancleCallBack!("NO");
      }

    }

  }


  //带边框的密码框.
  static Widget getEditFiledOfPw_Basic(
      TextEditingController textEditingController,
      bool passwordVisible,
      BuildContext context,
      String labelTx,
      String hintTx,
      String helperText,
      WkEventListener eventListener,
      {FormFieldValidator<String>? validator,
        int maxLength = 0}) {
    if (maxLength > 0) {
      return TextFormField(
          keyboardType: TextInputType.text,
          controller: textEditingController,
          obscureText: !passwordVisible, //This will obscure text dynamically
          decoration: InputDecoration(
              labelText: labelTx,
              hintText: hintTx,
              //下面是重点
              suffixIcon: IconButton(
                  icon: passwordVisible ? Image.asset('assets/images/textfiled_password_visisble.png',width: 48.w,height: 48.h,
                      color: Theme.of(context).primaryColorDark) :
                  Image.asset('assets/images/textfield_password_invisible.png' ,width: 48.w,height: 48.h,
                      color: Theme.of(context).primaryColorDark),
                  onPressed: () {
                    //更新状态控制密码显示或隐藏
                    eventListener.onClick!(passwordVisible);
                  })
          ),
          inputFormatters: [
            LengthLimitingTextInputFormatter(maxLength) //长度限制
          ],
          validator: validator);
    } else {
      return TextFormField(
          keyboardType: TextInputType.text,
          controller: textEditingController,
          obscureText: !passwordVisible, //This will obscure text dynamically
          decoration: InputDecoration(
            labelText: labelTx,
            hintText: hintTx,
            helperText: helperText,
            //下面是重点
            suffixIcon: IconButton(
                icon: passwordVisible ? Image.asset('assets/images/textfiled_password_visisble.png',width: 48.w,height: 48.h) :
                Image.asset('assets/images/textfield_password_invisible.png' ,width: 48.w,height: 48.h),
                onPressed: () {
                  //更新状态控制密码显示或隐藏
                  eventListener.onClick!(passwordVisible);
                }),
          ),
          validator: validator);
    }
  }

  // 带边框的密码框.
  static Widget getEditFiledOfPw(TextEditingController textEditingController,
      bool passwordVisible, BuildContext context, WkEventListener eventListener,
      {FormFieldValidator<String>? validator, int maxLength = 0}) {
    return getEditFiledOfPw_Basic(textEditingController, passwordVisible,
        context, "密码", "请输入密码", '', eventListener, validator: (v) {
          return v!.trim().isEmpty ? "密码不能为空" : null;
        }, maxLength: maxLength);
  }

  // 不带边框的密码框.
  static Widget getEditFiledOfPw_WithoutBoxWithHint(
      TextEditingController textEditingController,
      bool passwordVisible,
      BuildContext context,
      WkEventListener eventListener,
      String label,
      String hint) {
    return Container(
      width: 600.w,
      decoration: BoxDecoration(
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            spreadRadius: 5,
            blurRadius: 7,
            offset: Offset(0, 8.sp), // changes position of shadow
          ),
        ],
        color:Colors.white,
        borderRadius: BorderRadius.circular(45), // Optional: add border radius
      ),
      child: TextFormField(
          keyboardType: TextInputType.text,
          controller: textEditingController,
          obscureText: !passwordVisible, //This will obscure text dynamically
          decoration: InputDecoration(
              //labelText: label,
              hintText: hint,

              //下面是重点
              suffixIcon: IconButton(
                  icon: Icon(
                    //根据passwordVisible状态显示不同的图标
                      passwordVisible ? Icons.visibility : Icons.visibility_off,
                      color: Theme.of(context).primaryColorDark),
                  onPressed: () {
                    //更新状态控制密码显示或隐藏
                    eventListener.onClick!(passwordVisible);
                  }))),
    );
  }


  // 不带边框的密码框.
  static Widget getEditFiledOfPw_WithoutBox(
      TextEditingController textEditingController,
      bool passwordVisible,
      BuildContext context,
      WkEventListener eventListener) {
    return getEditFiledOfPw_WithoutBoxWithHint(textEditingController,
        passwordVisible, context, eventListener, "密码", "请输入密码");
  }



  static Widget getALine({int width = 150,int height = 20}) {
        return Container(
          decoration: BoxDecoration(
            color: AppColors.lineBgColor,
              borderRadius:BorderRadius.all(Radius.circular(10))
          ),
          child: SizedBox(width: width.w, height: height.h),
        );

  }


  static Widget getSmallALine() {
    return Container(
      decoration: BoxDecoration(
          color: AppColors.lineBgColor,
          borderRadius:BorderRadius.all(Radius.circular(10))
      ),
      child: SizedBox(width: 126.w, height: 12.h),
    );

  }


  static Divider getMyDivider() {
   return Divider(thickness:0.5,height: 1,color: AppColors.line_seperate_color);
  }


}
